package com.wjk.easy.view;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.clj.fastble.data.BleDevice;
import com.wjk.easy.R;
import com.wjk.easy.adapter.BlueDeviceScanAdapter;
import com.wjk.easy.blue.ConnectBlueTask;
import com.wjk.easy.blue.FastBleDeviceManager;
import com.wjk.easy.blue.PinBlueCallBack;
import com.wjk.easy.blue.PinBlueReceiver;
import com.wjk.easy.blue.rd915demo.UhfService;
import com.wjk.easy.ui.MainActivity;
import com.wjk.easy.utils.ScreenUtil;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import static com.wjk.easy.blue.FastBleService.DEVICE_TYPE_UHF;
import static com.wjk.easy.blue.rd915demo.UhfService.mBluetoothAdapter;

public class BlueScanListDialog extends Dialog {
    private Activity context;
    private EditText text_weight, text_remark, text_cardId, text_size_width, text_size_height, text_size_other;
    private View.OnClickListener mClickListener;
    private ProgressBar loadingBar;
    private String deviceType;
    public static final int MSG_BLUE_SCAN_FINISH = 42;
    public static final int MSG_BLUE_SCAN_STARTED = 43;
    public static final int MSG_BLUE_SCANNING = 44;
    private UhfService uhfService =  new UhfService();
    private boolean stopDiscover = true;

    public BlueScanListDialog(Activity context, String deviceType) {
        super(context);
        this.context = context;
        this.deviceType = deviceType;
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                //判断发送的消息
                case 0:
                    mAdapter.clear();
                    if(!UhfService.mBleArray.isEmpty()){
                        for(BluetoothDevice mdevice:UhfService.mBleArray) {
                            mAdapter.addUhfDevice(mdevice);
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                    break;
                case MSG_BLUE_SCAN_STARTED:
                    //Toast.makeText(context, "开始扫描蓝牙设备", Toast.LENGTH_SHORT).show();
                    break;
                case MSG_BLUE_SCANNING:
                    BleDevice bleDevice = (BleDevice) msg.obj;
                    mAdapter.addData(0,bleDevice);
                    break;
                case MSG_BLUE_SCAN_FINISH:
                    List<BleDevice> scanResultList = (List<BleDevice>) msg.obj;
                   // mAdapter.setDataList(scanResultList);
                    loadingBar.setVisibility(View.GONE);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 指定布局
        setContentView(R.layout.dialog_blue_scan_list);
        /*
         * 获取窗口对象及参数对象以修改对话框的布局设置, 可以直接调用getWindow(),表示获得这个Activity的Window
         * 对象,这样这可以以同样的方式改变这个Activity的属性.
         */
        Window dialogWindow = this.getWindow();
        WindowManager m = context.getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (ScreenUtil.getScreenHeight(context) * 0.7); // 高度设置为屏幕的0.6
        p.width = (int) (ScreenUtil.getScreenWidth(context) * 0.7);
        dialogWindow.setAttributes(p);
        dialogWindow.setBackgroundDrawableResource(R.drawable.bg_dialog);
        setCancelable(false);

        RecyclerView rv_list = findViewById(R.id.rv_list);
        loadingBar = findViewById(R.id.loading_scan);
        LinearLayoutManager dataManager = new LinearLayoutManager(context);
        rv_list.setLayoutManager(dataManager);
        rv_list.addItemDecoration(new RecycleViewDivider(
                context, LinearLayoutManager.HORIZONTAL, 4,
                context.getResources().getColor(R.color.trans)));

        mAdapter = new BlueDeviceScanAdapter(context, new ArrayList<BleDevice>());
        mAdapter.setOnItemClickListener(itemClick);
        rv_list.setAdapter(mAdapter);


        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        //蓝牙读卡器用（使用厂商提供的类）
        if(deviceType.equals(DEVICE_TYPE_UHF)){
            if(UhfService.nConnect) {
                uhfService.DisconnectBT();
            }
            stopDiscover=false;
            final long timeStart = new Date().getTime();
            uhfService.ScanBtDevice(!stopDiscover);
            final Thread thread=new Thread(new Runnable() {
                @Override
                public void run() {
                    while(!stopDiscover&&mHandler!=null) {
                        if(!UhfService.mBleArray.isEmpty()) {
                            mHandler.removeMessages(0);
                            mHandler.sendEmptyMessage(0);
                        }
                        long timeEnd = new Date().getTime();
                        if(timeEnd-timeStart>5000){
                            stopDiscover = true;
                            uhfService.ScanBtDevice(false);
                        }
                        SystemClock.sleep(500);
                    }

                }
            });
            thread.start();
        }else{
            //fastBleDeviceManager.startScan(mHandler);
            //经典蓝牙2.0

            IntentFilter filter = new IntentFilter();
            filter.addAction(BluetoothDevice.ACTION_FOUND);//搜索发现设备
            filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);//状态改变
            filter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);//行动扫描模式改变了
            filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);//动作状态发生了变化
            filter.addAction(BluetoothA2dp.ACTION_CONNECTION_STATE_CHANGED);
            filter.addAction(BluetoothA2dp.ACTION_PLAYING_STATE_CHANGED);

            context.registerReceiver(mBlueWeightDiscoverReceiver,filter);



            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice pairedDevice : pairedDevices) {
                    mAdapter.addUhfDevice(pairedDevice);
                }
            }
            if (!mBluetoothAdapter.isDiscovering()) {
                if (mBluetoothAdapter.startDiscovery()) {
                    Toast.makeText(context, "启动扫描中", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "启动扫描中失败", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }


    BluetoothDevice lastDevice;
    private final BroadcastReceiver mBlueWeightDiscoverReceiver = new BroadcastReceiver() {
        public void onReceive(final Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(lastDevice==null||!lastDevice.getAddress().equals(device.getAddress())){
                    mAdapter.addUhfDevice(device);
                    //这里我是扫描到需要的设备就停止扫描动作了。
                    if (device!=null&&!TextUtils.isEmpty(device.getName())) {
                        if (device.getName().equals("irxon")) {
                            mBluetoothAdapter.cancelDiscovery();
                        }
                    }
                    lastDevice = device;
                }
            }
        }
    };
    private BlueDeviceScanAdapter mAdapter;
    private OnDeviceClickListener itemClick = new OnDeviceClickListener(){
        @Override
        public void onClick(BleDevice device) {
            if(deviceType.equals(DEVICE_TYPE_UHF)){
                stopDiscover = true;
                uhfService.ScanBtDevice(false);
                uhfService.ConnectBT(device.getMac());
            }else{
                //判断设备是否配对，配对了就不需要配了
                if (device.getDevice().getBondState() == BluetoothDevice.BOND_NONE) {
                    Log.d("wjk", "attemp to bond:" + device.getName());
                    try {
                        Method createBondMethod = device.getDevice().getClass().getMethod("createBond");
                        Boolean returnValue = (Boolean) createBondMethod.invoke(device.getDevice());
                        returnValue.booleanValue();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.e("wjk", "attemp to bond fail!");
                    }
                }else{
                    Intent intent = new Intent("com.wjk.easy.BluetoothDevice.ACTION_BOND_STATE_CHANGED");
                    intent.putExtra(BluetoothDevice.EXTRA_DEVICE,device.getDevice());
                    context.sendBroadcast(intent);
                }
            }
            BlueScanListDialog.this.dismiss();
        }
    };
    public void onDetachedFromWindow() {
        Log.e("wjk","dialog detached from window");
        super.onDetachedFromWindow();
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler=null;
        }
        uhfService.ScanBtDevice(false);
        //fastBleDeviceManager.stopScan();
        if(!deviceType.equals(DEVICE_TYPE_UHF)){
            context.unregisterReceiver(mBlueWeightDiscoverReceiver);
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if(event.getKeyCode()==KeyEvent.KEYCODE_BACK){
            return super.dispatchKeyEvent(event);
        }
        return true;
    }

    public interface OnDeviceClickListener {
        void onClick(BleDevice device);
    }

    @Override
    public void onBackPressed() {
        if(isShowing()){
            dismiss();
        }
        super.onBackPressed();
    }
}
